﻿Imports System.Data
Imports System.Data.SqlClient

Namespace DB

    ''' <summary>
    ''' TypeName:    UserType
    ''' Author:      Waahid
    ''' DBTableName: SEC_Users
    ''' </summary>
    ''' <remarks></remarks>

    Public Class UserType
        Inherits DBTableObjectBase


#Region "Declarations"
        'Protected Friend iUserId as Guid
        Protected Friend iUserType As String = SEC_UserTypesEnum.User.ToString
        Protected Friend iUserName As String
        Protected Friend iPassword As String
        Protected Friend iPasswordVisible As String
        Protected Friend iAccessLevel As String = SEC_AccessLevelsEnum.Reception.ToString
        Protected Friend iDepartment As String
#End Region

#Region "Constructors"
        Public Sub New()
            MyBase.New(TableNamesEnum.SEC_Users)
        End Sub
        Public Sub New(ByVal UserId As Guid)
            MyBase.New(TableNamesEnum.SEC_Users, UserId)
        End Sub
        Public Sub New(ByVal UserId As Guid, _
                        ByVal UserType As String, _
                        ByVal UserName As String, _
                        ByVal Password As String, _
                        ByVal PasswordVisible As String, _
                        ByVal AccessLevel As String, _
                        ByVal Department As String, _
                        ByVal LMUserId As Guid, _
                        ByVal LMDate As DateTime)
            MyBase.New(TableNamesEnum.SEC_Users)
            Me.iId = UserId
            Me.iUserType = UserType
            Me.iUserName = UserName
            Me.iPassword = Password
            Me.iPasswordVisible = PasswordVisible
            Me.iAccessLevel = AccessLevel
            Me.iDepartment = Department
            Me.iLMUserId = LMUserId
            Me.iLMDate = LMDate

        End Sub
#End Region

#Region "Exposed Properties"
        Public Property UserId() As Guid
            Get
                Return Me.iId
            End Get
            Set(ByVal value As Guid)
                Me.iId = value
            End Set
        End Property
        Public Property UserType() As SEC_UserTypesEnum
            Get
                Return [Enum].Parse(GetType(SEC_UserTypesEnum), Me.iUserType.Replace(" ", "_"))
            End Get
            Set(ByVal value As SEC_UserTypesEnum)
                Me.iUserType = value.ToString.Replace("_", " ")
            End Set
        End Property
        Public Property UserName() As String
            Get
                Return Me.iUserName
            End Get
            Set(ByVal value As String)
                Me.iUserName = value
            End Set
        End Property
        Public Property PasswordVisible() As String
            Get
                Return Me.iPasswordVisible
            End Get
            Set(ByVal value As String)
                Me.iPasswordVisible = value
            End Set
        End Property
        Public Property AccessLevel() As SEC_AccessLevelsEnum
            Get
                If Me.iAccessLevel = String.Empty Then
                    Return Nothing
                Else
                    Return [Enum].Parse(GetType(SEC_AccessLevelsEnum), Me.iAccessLevel.Replace(" ", "_"))
                End If
            End Get
            Set(ByVal value As SEC_AccessLevelsEnum)
                Me.iAccessLevel = value.ToString.Replace("_", " ")
            End Set
        End Property
        Public Property Department() As String
            Get
                Return Me.iDepartment
            End Get
            Set(ByVal value As String)
                Me.iDepartment = value
            End Set
        End Property
#End Region

#Region "Implementations"
        Protected Friend Overloads Function Load(ByVal Row As DataRow) As Boolean
            If IsDBNull(Row(0)) Then Me.iId = Guid.Empty Else Me.iId = Row(0)
            If IsDBNull(Row(1)) Then Me.iUserType = Nothing Else Me.iUserType = Row(1)
            If IsDBNull(Row(2)) Then Me.iUserName = Nothing Else Me.iUserName = Row(2)
            If IsDBNull(Row(3)) Then Me.iPassword = Nothing Else Me.iPassword = Row(3)
            If IsDBNull(Row(4)) Then Me.iAccessLevel = Nothing Else Me.iAccessLevel = Row(4)
            If IsDBNull(Row(5)) Then Me.iDepartment = Nothing Else Me.iDepartment = Row(5)
            If IsDBNull(Row(6)) Then Me.iLMUserId = Nothing Else Me.iLMUserId = Row(6)
            If IsDBNull(Row(7)) Then Me.iLMDate = Nothing Else Me.iLMDate = Row(7)
            Me.iPasswordVisible = ""
            Return True
        End Function
        Protected Friend Overrides Function Load() As Boolean
            'sp_[TableName]Get
            Dim resBool As Boolean = True
            Dim da As New SqlDataAdapter
            Dim cmd As New SqlCommand("sp_" & Me.iTableName.ToString.Replace("COMP_", "") & "Get '" & Me.iId.ToString("D") & "'")
            cmd.Connection = Me.iConnection
            If IsNothing(Me.iTransaction) = False Then cmd.Transaction = Me.iTransaction

            Dim dt As DataTable = New DataTable
            dt = Utility.GetList(cmd)

            If dt.Rows.Count > 0 Then
                Me.Load(dt.Rows(0))
            Else
                resBool = False
            End If

            Me.iPasswordVisible = ""

            Return resBool
        End Function
        Protected Friend Overrides Function Insert() As Boolean
            'sp_[TableName]Insert
            Dim resBool As Boolean = True
            Dim resInt As Integer
            Dim da As New SqlDataAdapter

            Dim cmd As New SqlCommand("sp_" & Me.iTableName.ToString.Replace("COMP_", "") & "Insert")
            cmd.Connection = Me.iConnection
            If IsNothing(Me.iTransaction) = False Then cmd.Transaction = Me.iTransaction
            'Set command type to Stoed Procedure
            cmd.CommandType = CommandType.StoredProcedure
            'Validation or required parameters
            Try
                'Populate Stored Procedure parameters
                With cmd.Parameters
                    If (Me.iId = Guid.Empty) Then
                        .AddWithValue("@UserId", System.DBNull.Value)
                    Else
                        .AddWithValue("@UserId", Me.iId)
                    End If
                    If (Me.iUserType = String.Empty) Then
                        .AddWithValue("@UserType", System.DBNull.Value)
                    Else
                        .AddWithValue("@UserType", Me.iUserType)
                    End If
                    If (Me.iUserName = String.Empty) Then
                        .AddWithValue("@UserName", System.DBNull.Value)
                    Else
                        .AddWithValue("@UserName", Me.iUserName)
                    End If
                    'Hash password and erase it
                    Me.iPassword = Utility.HashBytes_SHA512(Me.iPasswordVisible)
                    If (Me.iPassword = String.Empty) Then
                        .AddWithValue("@Password", System.DBNull.Value)
                    Else
                        .AddWithValue("@Password", Me.iPassword)
                    End If
                    Me.iPasswordVisible = ""
                    If (Me.iAccessLevel = String.Empty) Then
                        .AddWithValue("@AccessLevel", System.DBNull.Value)
                    Else
                        .AddWithValue("@AccessLevel", Me.iAccessLevel)
                    End If
                    If (Me.iDepartment = String.Empty) Then
                        .AddWithValue("@Department", System.DBNull.Value)
                    Else
                        .AddWithValue("@Department", Me.iDepartment)
                    End If
                    If (Me.iLMUserId = Guid.Empty) Then
                        .AddWithValue("@LMUserId", System.DBNull.Value)
                    Else
                        .AddWithValue("@LMUserId", Me.iLMUserId)
                    End If
                    If (Me.iLMDate = DateTime.MinValue) Then
                        .AddWithValue("@LMDate", System.DBNull.Value)
                    Else
                        .AddWithValue("@LMDate", Me.iLMDate)
                    End If
                End With
                'Execute Stored Procedure
                resInt = cmd.ExecuteNonQuery()
            Catch ex As Exception
                resBool = False
                Throw ex
            End Try
            If resInt = 0 Then
                Dim ex As New RequestedRecordDoesNotExistException("Requested changes failed to insert, no records were modified")
            End If
            Return resBool
        End Function
        Protected Friend Overrides Function Update() As Boolean
            'sp_[TableName]Update
            Dim resBool As Boolean = True
            Dim resInt As Integer
            Dim da As New SqlDataAdapter
            Dim cmd As New SqlCommand("sp_" & Me.iTableName.ToString.Replace("COMP_", "") & "Update")
            cmd.Connection = Me.iConnection
            If IsNothing(Me.iTransaction) = False Then cmd.Transaction = Me.iTransaction
            'Set command type to Stoed Procedure
            cmd.CommandType = CommandType.StoredProcedure
            'Validation or required parameters
            Try
                'Populate Stored Procedure parameters
                With cmd.Parameters
                    If (Me.iId = Guid.Empty) Then
                        .AddWithValue("@UserId", System.DBNull.Value)
                    Else
                        .AddWithValue("@UserId", Me.iId)
                    End If
                    If (Me.iUserType = String.Empty) Then
                        .AddWithValue("@UserType", System.DBNull.Value)
                    Else
                        .AddWithValue("@UserType", Me.iUserType)
                    End If
                    If (Me.iUserName = String.Empty) Then
                        .AddWithValue("@UserName", System.DBNull.Value)
                    Else
                        .AddWithValue("@UserName", Me.iUserName)
                    End If
                    'Hash password and erase it
                    Me.iPassword = Utility.HashBytes_SHA512(Me.iPasswordVisible)
                    If (Me.iPassword = String.Empty) Then
                        .AddWithValue("@Password", System.DBNull.Value)
                    Else
                        .AddWithValue("@Password", Me.iPassword)
                    End If
                    Me.iPasswordVisible = ""
                    If (Me.iAccessLevel = String.Empty) Then
                        .AddWithValue("@AccessLevel", System.DBNull.Value)
                    Else
                        .AddWithValue("@AccessLevel", Me.iAccessLevel)
                    End If
                    If (Me.iDepartment = String.Empty) Then
                        .AddWithValue("@Department", System.DBNull.Value)
                    Else
                        .AddWithValue("@Department", Me.iDepartment)
                    End If
                    If (Me.iLMUserId = Guid.Empty) Then
                        .AddWithValue("@LMUserId", System.DBNull.Value)
                    Else
                        .AddWithValue("@LMUserId", Me.iLMUserId)
                    End If
                    If (Me.iLMDate = DateTime.MinValue) Then
                        .AddWithValue("@LMDate", System.DBNull.Value)
                    Else
                        .AddWithValue("@LMDate", Me.iLMDate)
                    End If
                End With
                'Execute Stored Procedure
                resInt = cmd.ExecuteNonQuery()
            Catch ex As Exception
                resBool = False
                Throw ex
            End Try
            If resInt = 0 Then
                Throw New RequestedRecordDoesNotExistException("Requested changes failed to update, no records were modified")
            End If
            Return resBool
        End Function
        Protected Friend Overrides Function ValidateOnDelete() As Boolean
            Return True
        End Function
        Protected Friend Overrides Function ValidateOnInsert() As Boolean
            Return True
        End Function
        Protected Friend Overrides Function ValidateOnUpdate() As Boolean
            Return True
        End Function
#End Region

#Region "Overrides"
        Public Overrides Function ToString() As String
            Return Me.iUserName & " (" & Me.iAccessLevel & ")"
        End Function
        Public Overrides Function ToDetailsListBoxItem() As WindowsExtendedControls.DetailListBoxItem
            Return Nothing
        End Function
#End Region


    End Class

    Public Class UserTypeCollection
        Inherits DBTableObjectCollectionBase

        Public DataFilters As New DataFilterTypeCollection(Of UserTypeFields)(Me.iTablename.ToString)
        Public DataSorters As New DataSorterTypeCollection(Of UserTypeFields)(Me.iTableName.ToString)

        Public Sub New()
            MyBase.New(TableNamesEnum.SEC_Users)
        End Sub

        Default Public Property Item(ByVal Index As Integer) As UserType
            Get
                Return CType(Me.List.Item(Index), UserType)
            End Get
            Set(ByVal value As UserType)
                Me.List.Item(Index) = value
            End Set
        End Property

        Protected Friend Overrides Function Load() As Boolean
            Return Me.Load("SELECT * FROM " & Me.iTableName.ToString & Me.DataFilters.GetSQL & Me.DataSorters.GetSQL)
        End Function

        Protected Friend Overloads Function Load(ByVal CustomFilter As String) As Boolean
            'Get data from DB
            Dim cmd As New SqlCommand
            cmd.Connection = Me.iConnection
            If IsNothing(Me.iTransaction) = False Then cmd.Transaction = Me.iTransaction
            Dim dt As DataTable
            Try
                cmd.CommandText = CustomFilter
                dt = Utility.GetList(cmd)
            Catch ex As Exception
                Throw ex
            End Try
            'Clear exising list
            Dim row As DataRow
            List.Clear()

            'Build new list
            Dim typeObject As UserType

            For Each row In dt.Rows
                typeObject = New UserType()
                typeObject.iConnection = Me.iConnection
                typeObject.iTransaction = Me.iTransaction
                If typeObject.Load(row) = True Then Me.List.Add(typeObject)
            Next
            Return True
        End Function

        Public Overloads Sub Sort(ByVal propertyToSort As UserTypeFields, ByVal sortOrder As SortOrder)
            ipropertyToSort = propertyToSort.ToString
            isortOrder = sortOrder
            Me.InnerList.Sort(Me)
        End Sub

    End Class

#Region "Enumerations"       'Enumerations
    Public Enum UserTypeFields
        UserId
        UserType
        UserName
        Password
        PasswordVisible
        AccessLevel
        Department
        LMUserId
        LMDate

    End Enum
#End Region

End Namespace